/**
* <p>Title: ResourceService.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2015</p>
* <p>Company: SiySoft</p>
* @author liguanghui
* @date 2015年6月2日
* @version 1.0
*/
package com.siysoft.tc.base.service.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.siysoft.tc.base.bean.to.Resource;
import com.siysoft.tc.base.service.IResourceService;
import com.siysoft.util.COMMON;
import com.siysoft.util.fileupload.FileUtil;
import com.tc.base.dao.BaseDAO;

/**
 * <p>Title: ResourceService</p>
 * <p>Description: </p>
 * <p>Company: SiySoft</p>
 * @author    liguanghui
 * @date       2015年6月2日
 */
@Service
public class ResourceServiceImpl implements IResourceService {

	@Autowired
	BaseDAO baseDao;
	
	@Value("${file.imageUploadDir}")
	private String defaultDir;
	/* （非 Javadoc）
	 * <p>Title: getResourceUrl</p>
	 * <p>Description: </p>
	 * @param resType
	 * @param targetId
	 * @return
	 * @see com.siysoft.yihaoxue.base.service.IResourceService#getResourceUrl(java.lang.String, int)
	 */
	@Override
	public String getResourceUrl(String resType, int targetId) throws Exception {
		String sql="from Resource where dataType='"+resType+"' and dataId="+targetId;
		List<Resource> resource=baseDao.findByHQL(sql);
		if(resource.size()==0){
			return null;
		}
		return COMMON.home_url + resource.get(0).getImgPath();
		
	}
	/* （非 Javadoc）
	* <p>Title: insertResource</p>
	* <p>Description: </p>
	* @param resource
	* @see com.siysoft.yihaoxue.base.service.IResourceService#insertResource(com.siysoft.yihaoxue.base.service.Resource)
	*/
	@Override
	public void insertResource(Resource resource,MultipartFile file) {
		String filename=this.generateFilename(file);
		String relFilename=this.getRelativePath(filename);
		String fullPath=this.getFullPath(filename);
		
		try {
			FileUtil.save(file, fullPath);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		resource.setImgPath(relFilename);
		baseDao.save(resource);
	}

	/**
	 * 方法摘要：根据MultipartFile 生成唯一文件名 
	 * 作者：liguanghui
	 * 日期：2015年6月9日 上午10:48:04
	 * @param file
	 * @return 带后缀的文件名
	 */
	@Override
	public String generateFilename(MultipartFile file){
		String filename=String.valueOf(System.currentTimeMillis())+String.valueOf(file.hashCode());
		String suffix=file.getOriginalFilename().substring  
				(file.getOriginalFilename().lastIndexOf("."));
		return filename+suffix;
	}
	@Override
	public String getFullPath(String filename){
		String dir= this.getClass().getResource("/").getPath().replace("WEB-INF/classes/", "");
		return dir+defaultDir+"/"+filename;
	}
	/**
	 * 方法摘要： 根据文件名获取相对路径
	 * 作者：liguanghui
	 * 日期：2015年6月9日 上午10:48:59
	 * @param filename
	 * @return
	 */
	@Override
	public String getRelativePath(String filename){
		return defaultDir+"/"+filename;
	}
	/* （非 Javadoc）
	* <p>Title: updateResource</p>
	* <p>Description: </p>
	* @param resource
	* @see com.siysoft.yihaoxue.base.service.IResourceService#updateResource(com.siysoft.yihaoxue.base.bean.to.Resource)
	*/
	@Override
	public void updateResource(Resource resource) {
		
		
	}
	/* （非 Javadoc）
	* <p>Title: generateFilename</p>
	* <p>Description: </p>
	* @param filesuffix
	* @return
	* @see com.siysoft.yihaoxue.base.service.IResourceService#generateFilename(java.lang.String)
	*/
	@Override
	public String generateFilename(String filesuffix) {
		String filename=String.valueOf(System.currentTimeMillis())+String.valueOf(Math.random()*25+97);
		String suffix="."+filesuffix;
		return filename+suffix;
	}
	/* （非 Javadoc）
	* <p>Title: insertResource</p>
	* <p>Description: </p>
	* @param resource
	* @param base64
	* @see com.siysoft.yihaoxue.base.service.IResourceService#insertResource(com.siysoft.yihaoxue.base.bean.to.Resource, java.lang.String)
	*/
	@Override
	public void insertResource(Resource resource, String base64) {
		//生成唯一文件名
		String filename=this.generateFilename("png");
		//获取相对路径
		String relFilename=this.getRelativePath(filename);
		//获取绝对路径
		String fullPath=this.getFullPath(filename);
		
		try {
			FileUtil.save(base64,this.getimgPath(),filename);
	
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		resource.setImgPath(relFilename);
		baseDao.save(resource);
		
	}
	/* （非 Javadoc）
	* <p>Title: getimgPath</p>
	* <p>Description: </p>
	* @return
	* @see com.siysoft.yihaoxue.base.service.IResourceService#getimgPath()
	*/
	@Override
	public String getimgPath() {
		
		return this.getClass().getResource("/").getPath().replace("WEB-INF/classes","")+"\\"+this.defaultDir;
	}
	/**
	 * 根据图片类型和userId 获取图片路径
	 */
	@Override
	public Resource getResource(String resType, int targetId) throws Exception {
		String sql="from Resource where dataType='"+resType+"' and dataId="+targetId;
		List<Resource> resources=baseDao.findByHQL(sql);
		if(resources.size()==0){
			return null;
		}
		return resources.get(0);
	}

	@Override
	public void changeResource(Resource resource, String local) {
		String hql= "from Resource a where a.dataType='"+resource.getDataType()+"' AND a.userId="+resource.getUserId();
		List<Resource> resourcelist =baseDao.findByHQL(hql);
		if(resourcelist.size()!=0){
			try {
				FileUtil.delete(local + resourcelist.get(0).getImgPath());
			} catch (FileNotFoundException e) {
				System.out.println("文件不存在");
			}
		}
		resource.setImgPath(resource.getImgPath().substring(1));
		Resource resource1=resource;
		if(resourcelist.size()!=0){
			resource1=resourcelist.get(0);
			resource1.setUploadTime(resource.getUploadTime());
			resource1.setImgPath(resource.getImgPath());
		}
		
		baseDao.saveOrupdate(resource1);
		
	}
	@Override
	public Resource getResourceById(int resourceId) throws Exception {
		// TODO Auto-generated method stub
		return (Resource) baseDao.findById(Resource.class, resourceId);
	}

}
